package danny.hoi.web.controller.admin;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import danny.hoi.domain.export.admin.Company;
import danny.hoi.domain.export.admin.CompanyExample;
import danny.hoi.service.admin.CompanyService;
import danny.hoi.web.controller.base.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/company")
public class CompanyController extends BaseController {

    @Reference(timeout = 100000)
    private CompanyService companyService;

    /**
     * 1.分页显示企业信息
     * 2.请求地址:company/list.do
     * 3.响应地址:WEB-INF/pages/company/company-list.jsp
     */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize,
                       String key) {
        if (key == null) {
            key = "";
        }
        CompanyExample example = new CompanyExample();
        CompanyExample.Criteria criteria = example.createCriteria();
        //设置条件查询
        criteria.andNameLike("%" + key + "%");

        PageInfo<Company> pageInfo = companyService.findByPages(example, pageNum, pageSize);

        request.setAttribute("key", key);
        request.setAttribute("pageInfo", pageInfo);
        return "company/company-list";
    }

    /**
     * 1.前往添加页面
     * 2.请求地址:/company/toAdd.do
     * 3.响应地址:WEB-INF/pages/company/company-add.jsp
     */
    @RequestMapping("/toAdd")
    public String toAdd() {
        return "company/company-add";
    }

    /**
     * 1.前往修改页面
     * 2.请求地址:/company/toUpdate.do
     * 3.响应地址:WEB-INF/pages/company/company-update.jsp
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        Company company = companyService.findById(id);
        request.setAttribute("company", company);
        return "company/company-update";
    }


    /**
     * 1.更新页面
     * 2.请求地址:/company/edit.do
     * 3.响应地址:redirect:/company/list.do
     */
    @RequestMapping("/edit")
    public String edit(Company company) {
        if (StringUtils.isEmpty(company.getId())) {
            //添加
            companyService.save(company);
        } else {
            //更新
            companyService.update(company);
        }

        return "redirect:/company/list.do";
    }

    /**
     * 1.删除
     * 2.请求地址: "/company/delete.do?id=" + id;
     * 3.响应地址: return "redirect:/company/list.do";
     */
    @RequestMapping("/delete")
    public String delete(String id) {
        companyService.delete(id);
        return "redirect:/company/list.do";
    }

}
